from protorpc import remote
from http.request.userRequest import UserRequest
from http.response.userResponse import UserResponse
from model.user import User
from datetime import date
import logging

# Create the RPC service to exchange messages
class UserService(remote.Service):

        @remote.method(UserRequest, UserResponse)
    	def put(self, request):
            
	    exist = self.check(request.email)
            
	    if(not exist):
            	user = User(key_name = request.email)
            	user.first_name = request.first_name
            	user.last_name =  request.last_name
            	user.email = request.email
	    	user.password = request.password
            	user.last_update = date.today()
	    	user.is_active = True
            	user.put()

            return UserResponse(first_name='First name: %s!' % request.first_name)


	@remote.method(UserRequest, UserResponse)
    	def get(self, request):
            try:
	        users = User.all()
            	users.filter("email =", request.email)
            	users.filter("password =", request.password)
            	for user in users.run():
                    logging.debug(user.last_name)
                return UserResponse(first_name=user.first_name, last_name=user.last_name)
	     
            except:	
                return UserResponse(message = "User or password is wrong")


        def check(self, key):
	    try:
	    	user = User.get_by_key_name(key)
            	logging.debug("User: "  + user.first_name)
                return True
	    except:
		logging.debug("User don't exist")
		return False



